<template>
  <div>
    <el-form class="query-form"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true">
      <!-- <el-col :sm="8" :lg="6" :xl="4"> -->
      <el-form-item label="渠道" prop="channel_id">
        <el-cascader
        v-model="queryParams.channel_id"
        :options="permission_projectList"
        :props="{ multiple: true,emitPath:false }"
        collapse-tags
        clearable
        filterable
        @change="handleQuery"></el-cascader>
      </el-form-item>
      <el-form-item label="支付方式"
        prop="pay_type">
        <el-select v-model="queryParams.pay_type"
          placeholder="请选择"
          @change="handleQuery">
          <el-option
            label="全部"
            :value="null"/>
           <el-option v-for="item in payTypeOptions" :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态"
        prop="status">
        <el-select v-model="queryParams.status"
          placeholder="请选择"
          @change="handleQuery">
          <el-option key="all"
            label="全部"
            :value="null"/>
          <el-option v-for="([key, value], index) in orderStatus"
            :key="index"
            :label="value.desc"
            :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单金额">
        <el-input-number v-model="numberRange.pay_amount_begin"
          placeholder="最低价"
          size="small"
          :precision="2"
          style="width: 80px"/>
        -
        <el-input-number v-model="numberRange.pay_amount_end"
          placeholder="最高价"
          size="small"
          :precision="2"
          style="width: 80px"/>
      </el-form-item>
      <el-form-item class="big-query" label="创建订单时间" prop="createDateRange">
        <el-date-picker v-model="queryParams.createDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="big-query" label="支付时间">
        <el-date-picker v-model="payDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="big-query" label="关键词"
        prop="keyword">
        <el-input v-model="queryParams.keyword"
          placeholder="输入订单号、用户ID、手机号"
          size="small"
          style="width:240px"
          clearable
          @keyup.enter.native="handleQuery"
          @clear="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          size="small"
          @click="handleQuery">搜索</el-button>
        <el-button
          size="small"
          @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading"
      @sort-change="onSortChange"
      :data="orderList">
      <!-- 新增 -->
      <el-table-column label="父订单号"
        min-width="210"
        prop="parent_order_no" />
      <el-table-column label="绑定手机号"
        width="120"
        prop="user_phone" />
      <el-table-column label="下单人昵称"
        width="110"
        show-overflow-tooltip=""
        prop="user_nick" />
      <el-table-column label="下载渠道"
        width="120"
        prop="channel_id">
         <template #default="{ row }">
          <span>{{ row.channel_id |  translateToName(channelOptions, 'channel_id', 'name')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式"
        width="100"
        prop="pay_type">
        <template slot-scope="scope">
          <el-tag :type="scope.row.pay_type === 2 ? 'success':scope.row.pay_type === 1?'' :'info'"
            disable-transitions>{{ typeFormat(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单名称"
        min-width="170"
        prop="product_name" />
      <el-table-column label="订单金额"
        width="100"
        prop="pay_price"
        sortable="custom">
        <template #default = {row}>
          {{ row.pay_price | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="创建订单时间"
        min-width="160"
        show-overflow-tooltip
        prop="create_time" />
      <el-table-column label="支付订单时间"
        min-width="160"
        show-overflow-tooltip
        prop="pay_time"
        sortable="custom"/>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="orderStatus.get(scope.row.status).tagType"
            disable-transitions>{{ orderStatus.get(scope.row.status).desc }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"
        fixed="right"
        width="90"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" :disabled="scope.row.status!==2" @click="handleRefund(scope.row)">退款</el-button>
          <el-button size="small"
            type="text"
            @click="handleDetail(scope.row)">详情</el-button>
          <!-- <el-button size="small" type="text">查看数据统计</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="total>0"
      :total="total"
      layout="total,slot,sizes,prev,pager,next,jumper"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList">
      <span class="span-amount">共 {{amount|formatMoney}} 元</span>
      <span class="span-amount">平均每单 {{(amount/total)|formatMoney}} 元</span>
    </pagination>
      <!-- 订单详情 -->
      <el-dialog title="订单详情" :visible.sync="open" width="700px" :close-on-click-modal="false">
        <orderDetail :orderInfo="orderInfo" :payTypeOptions="payTypeOptions" :channelOptions="channelOptions"/>
      </el-dialog>
    <AuthCode :visible.sync="openAuth" ref="AuthCode" :title="authTitle" :authObj="authObj" @submit="submitRefund"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Axios from 'axios'
import AuthCode from '@/components/auth-code'
import { listOrder, getOrder, refundOrder } from '@/api/order/order'
import { getChannelByAppId } from '@/api/system/channel'
import { sendCode } from '@/api/member/product'
import { parseTime } from '@/utils'
import orderDetail from './components/order-detail.vue'
import { getOrderStatus } from '@/constants/constant'
export default {
  name: 'Order',
  components: { AuthCode, orderDetail },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 总金额
      amount: 0,
      // 表格数据
      orderList: null,
      // 渠道选择
      channelOptions: [],
      payTypeOptions: [],
      // 是否显示弹出层
      open: false,
      authTitle: '',
      openAuth: false,
      orderStatus: null,
      // 表单参数
      orderInfo: {},
      authObj: {},
      // 查询参数 - 支付时间
      payDateRange: undefined,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        product_type: 3,
        channel_id: null,
        pay_type: null,
        status: 2,
        // 查询参数 - 订单创建时间
        createDateRange: null
        // member_deadline: 10
      },
      // 查询数字区间参数
      numberRange: {
        pay_amount_begin: undefined,
        pay_amount_end: undefined
      }
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  },
  created () {
    const now = parseTime(new Date(), '{y}-{m}-{d}')
    const list = this.permission_projectList.map(item => item.app_id)
    this.queryParams.createDateRange = [now, now]
    this.orderStatus = getOrderStatus()
    Axios.all([this.getListApi(), getChannelByAppId({ app_ids: list.join(',') })]).then(Axios.spread((res1, res2) => {
      const channelList = res2.data.list
      for (const item of this.permission_projectList) {
        item.label = item.name
        item.value = parseInt(item.app_id)
        const list = channelList.filter(item1 => item1.AppId?.includes(item.value))
        item.children = list.map(item => ({ label: item.channel_id + item.name, value: item.channel_id }))
      }
      this.channelOptions = res2.data.list
      this.orderList = res1
    }))
    this.getDicts('pay_method').then(res => {
      this.payTypeOptions = (res.data || []).map(item => {
        item.dictValue = parseInt(item.dictValue) || 0
        return item
      })
    })
  },
  methods: {
    getListApi () {
      let { payDateRange } = this
      const createDate = this.addDateRange(this.queryParams.createDateRange, 'create_begin', 'create_end')
      const payDate = this.addDateRange(payDateRange, 'pay_begin', 'pay_end')
      Object.assign(this.queryParams, createDate, payDate)
      this.loading = true
      return new Promise((resolve, reject) => {
        listOrder(this.queryParams).then(response => {
          const data = response.data || {}
          resolve(data.list)
          this.amount = data.amount
          this.total = data.count || 0
        }).finally(() => {
          this.loading = false
        })
      })
    },
    getList () {
      this.getListApi().then(res => {
        this.orderList = res
      })
    },
    // 支付方式内置字典翻译
    typeFormat (row, column) {
      return this.selectDictLabel(this.payTypeOptions, row.pay_type)
    },
    /** 搜索按钮操作 */
    handleQuery () {
      let { queryParams, numberRange } = this
      const isValid = this.validNumberRangeInput(queryParams, 'pay_amount_begin', 'pay_amount_end')
      if (!isValid) {
        this.msgError('请检查数字区间输入')
        return
      }
      this.queryParams.page = 1
      Object.keys(numberRange).forEach(key => {
        const item = numberRange[key]
        this.queryParams[key] = item ? item * 100 : undefined
      })
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.payDateRange = []
      Object.keys(this.numberRange).forEach(key => {
        this.numberRange[key] = undefined
      })
      this.resetForm('queryForm')
      this.handleQuery()
    },
    onSortChange ({ prop, order }) {
      this.queryParams.sort_field = order ? prop : null
      this.queryParams.sort_method = order === 'descending' ? 'desc' : 'asc'
      this.getList()
    },
    handleRefund (row) {
      this.authObj = {
        type: 'refund',
        data: {
          order_no: row.parent_order_no
        }
      }
      sendCode(Object.assign({ mock: true }, this.authObj)).then(res => {
        if (res.data.need_verify) {
          this.authTitle = `确定将订单${row.parent_order_no}进行退款吗？验证码通过验证后才可进行操作`
          this.openAuth = true
        } else {
          this.submitRefund({
            code: res.data.code,
            vid: res.data.vid
          })
        }
      })
    },
    submitRefund (codeObj) {
      refundOrder({ order_no: this.authObj.data.order_no }, codeObj).then(() => {
        this.$message({
          type: 'success',
          message: '退款成功!'
        })
        this.openAuth = false
        this.getList()
      }).catch(e => {
        if (e?.data?.data?.sub_code === 'not_enough') {
          this.$message.closeAll()
          this.handleConfirmRefund({ order_no: this.authObj.order_no }, codeObj)
        }
        this.$refs.AuthCode.cancelLoading()
      })
    },
    handleConfirmRefund (row, codeObj) {
      this.$confirm(`用户剩余智币不足退款，是否进行强制退款`, '强制退款', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        refundOrder({
          order_no: row.order_no,
          force: true
        // eslint-disable-next-line sonarjs/no-identical-functions
        }, codeObj).then(() => {
          this.$message({
            type: 'success',
            message: '退款成功!'
          })
          this.getList()
        })
      })
    },
    /** 查看详情 */
    handleDetail (row) {
      this.loading = true
      getOrder(row.order_no).then(response => {
        this.orderInfo = response.data
        this.open = true
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
